package com.koala.web.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class OssUtil {

    private final OSS ossClient;

    @Value("${alibaba.cloud.oss.endpoint}")
    private String endpoint;

    @Value("${alibaba.cloud.oss.bucket:your-default-bucket}") // 可在 yml 里加 bucket
    private String bucketName;

    @Value("${alibaba.cloud.access-key}")
    private String accessKey;

    @Value("${alibaba.cloud.secret-key}")
    private String secretKey;

    public OssUtil(OSS ossClient) {
        this.ossClient = ossClient;
    }

    /**
     * 上传文件（MultipartFile）
     */
    public String upload(MultipartFile file, String folder) throws Exception {
        String original = file.getOriginalFilename();
        String ext = "";
        if (original != null && original.contains(".")) {
            ext = original.substring(original.lastIndexOf("."));
        }

        String key = buildKey(folder, ext);
        try (InputStream in = file.getInputStream()) {
            ossClient.putObject(new PutObjectRequest(bucketName, key, in));
        }
        return buildUrl(key);
    }

    /**
     * 上传 InputStream
     */
    public String upload(InputStream stream, String folder, String ext) {
        String key = buildKey(folder, ext);
        ossClient.putObject(new PutObjectRequest(bucketName, key, stream));
        return buildUrl(key);
    }

    /**
     * 删除文件
     */
    public void delete(String key) {
        ossClient.deleteObject(bucketName, key);
    }

    /**
     * 生成带签名的临时访问链接
     */
    public String generateSignedUrl(String key, long expireSeconds) {
        Date expiration = new Date(System.currentTimeMillis() + expireSeconds * 1000);
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        return url.toString();
    }

    private String buildKey(String folder, String ext) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String date = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        return String.format("%s/%s/%s%s", folder, date, uuid, ext);
    }

    private String buildUrl(String key) {
        return String.format("https://%s.%s/%s", bucketName, endpoint, key);
    }
}
